<?php
/**
 * Created by PhpStorm.
 * User: WJP
 * Date: 2019-04-10
 * Time: 22:25
 */
/**
 *	 socket面向对象的编译
 */
class Ws
{
    CONST HOST='0.0.0.0';
    CONST PORT='9501';
    public $ws=null;

    public function __construct()
    {
        $this->ws=new swoole_http_server(self::HOST,self::PORT);
        $this->ws->set([
            //启动task必须要设置其数量
            'worker_num' => 4,
            'task_worker_num' => 4,
        ]);
        $this->ws->on('workerStart',[$this,'onWorkerStart']);
        $this->ws->on('request',[$this,'onRequest']);
        $this->ws->on('task',[$this,'onTask']);
        $this->ws->on('finish',[$this,'onFinish']);
        $this->ws->on('close',[$this,'onclose']);
        $this->ws->start();
    }

    /**
    监听开启事件的回调
     */
    public function onWorkerStart($server, $worker_id)
    {
        // 定义应用目录
        define('APP_PATH', __DIR__ . '/../application/');
        // 加载框架里面的文件
        require __DIR__ . '/../thinkphp/base.php';
    }

    /**
     * request回调
     * @param $request
     * @param $response
     */
    public function onRequest($request, $response) {
        $_SERVER  =  [];
        if(isset($request->server)) {
            foreach($request->server as $k => $v) {
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        if(isset($request->header)) {
            foreach($request->header as $k => $v) {
                $_SERVER[strtoupper($k)] = $v;
            }
        }

        $_GET = [];
        if(isset($request->get)) {
            foreach($request->get as $k => $v) {
                $_GET[$k] = $v;
            }
        }
        $_POST = [];
        if(isset($request->post)) {
            foreach($request->post as $k => $v) {
                $_POST[$k] = $v;
            }
        }
        $_POST['http_server'] = $this->ws;

        ob_start();
        // 执行应用并响应
        try {
            think\Container::get('app', [APP_PATH])
                ->run()
                ->send();
        }catch (\Exception $e) {
            // todo
        }

        $res = ob_get_contents();
        ob_end_clean();
        $response->end($res);
    }
    /**
    监听关闭事件的回调
     */
    public function onclose($ser, $fd)
    {
        print_r("你好,我的{$fd}\n");
    }

    /**
     *	$serv 			服务
     *	$task_id		任务ID，由swoole扩展内自动生成，用于区分不同的任务
     *	$src_worker_id 	$task_id和$src_worker_id组合起来才是全局唯一的，不同的worker进程投递的任务ID可能会有相同
     *	$data 			是任务的内容
     */
    public function onTask($serv,$task_id,$src_worker_id,$data)
    {
        //在终端输出
        print_r($data).'/n';
        //执行耗时任务
        sleep(10);
        //回调于onFinish
        return '你成了-A';
    }
    /**
     *	$task_id 		是任务的ID
     *	$data			是任务处理的结果内容
     */
    public function onFinish($serv,$task_id,$data)
    {
        print_r($data).'/n';
    }

}

new Ws();

